<?php


namespace app\http\middleware;




use app\admin\service\AdminUserService;
use app\common\model\StaffAccount;
use app\common\model\StaffRole;
use app\Request;
use app\services\jwt\JwtService;
use app\services\UserToken\UserTokenService;

class AdminCheckToken
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle(Request $request, \Closure $next)
    {
        if(is_null($request->header('Authorization'))){
            return error('未登录','401');
        }
        if(empty($request->header('Authorization'))){
            return error('未登录','401');
        }
        $token = $request->header('Authorization');
        //没有token
        if (!$token){
            return error('未登录','401');
        }
        //没有找到jwt类
        $jwt=new JwtService();
        try {
            $decode=$jwt->checkToken($token);
        }catch (\Exception $e){
            return error('登录已过期，请重新登录','401');
        }
        //解析token
        $decode=json_decode(json_encode($decode),true);


        if (!$decode){
            //$authInfo->delete();
            return error("登录状态有误,请重新登录",[],401);
        }
        //
        $userTokenService = new UserTokenService();
        $userTokenResult = $userTokenService->getUserToken(['uid' => $decode['admin_id'],'type' => 2,'token'=>$token]);
        if (empty($userTokenResult['data'])){
            return error("登录状态有误,请重新登录",[],'401');
        }
        if ( $userTokenResult['data']['effective_time']< time()){
            return error("token已过期",[],'401');
        }
        $adminUserService = new AdminUserService();
        $adminUser = $adminUserService->getAdminUser($userTokenResult['data']['uid']);
        if(!$adminUser['data']){
            return error("登录状态有误,请重新登录",[],'401');
        }
        if($adminUser['data']['status'] !== 1){
            return error("账号未启用,请联系管理员",[],'401');
        }
        $request->admin_id =$decode['admin_id'];
        return $next($request);


    }
}